package soft.quicknote.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import org.joda.time.LocalDateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

import java.sql.Timestamp;
import java.util.ArrayList;

import soft.quicknote.DBHelper;
import soft.quicknote.R;
import soft.quicknote.beans.Note;

public class NoteAdapter extends ArrayAdapter<Note> {

    private static final DateTimeFormatter FORMATTER = DateTimeFormat.forPattern("yyyy年MM月dd日 HH时mm分ss秒");
    DBHelper helper;

    // View lookup cache
    private static class ViewHolder {
        TextView title;
        TextView category;
        TextView time;
    }

    public NoteAdapter(Context context, ArrayList<Note> notes) {
        super(context, 0, notes);
        helper = new DBHelper(context);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        Note note = getItem(position);

        ViewHolder viewHolder;
        if (convertView == null) {
            viewHolder = new ViewHolder();
            LayoutInflater inflater = LayoutInflater.from(getContext());
            convertView = inflater.inflate(R.layout.item_note, parent, false);
            viewHolder.time = (TextView) convertView.findViewById(R.id.note_item_time);
            viewHolder.title = (TextView) convertView.findViewById(R.id.note_item_title);
            viewHolder.category = (TextView) convertView.findViewById(R.id.note_item_category);
            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }

        viewHolder.title.setText(note.getTitle());

        Timestamp ts = new Timestamp(note.getUpdateTime());
        LocalDateTime dateTime = LocalDateTime.fromDateFields(ts);

        viewHolder.time.setText(dateTime.toString(FORMATTER));

        String cat = helper.querySingleCategory(note.getCategory());
        viewHolder.category.setText(cat == null ? "无" : cat);
        return convertView;
    }
}
